package com.icebartech.base.modules.user.api;

import com.github.pagehelper.PageInfo;
import com.icebartech.base.modules.user.dto.AppPermissionInfoDTO;
import com.icebartech.base.modules.user.dto.AppRoleInfoDTO;
import com.icebartech.base.modules.user.model.AppRole;
import com.icebartech.base.modules.user.service.AppPermissionService;
import com.icebartech.base.modules.user.service.AppRoleService;
import com.icebartech.core.annotations.RequireLogin;
import com.icebartech.core.constants.UserEnum;
import com.icebartech.core.controller.BaseController;
import com.icebartech.core.local.LocalUser;
import com.icebartech.core.local.UserThreadLocal;
import com.icebartech.core.vo.BaseData;
import com.icebartech.core.vo.PageData;
import com.icebartech.core.vo.RespJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 后台角色管理controller
 * @author wenhsh
 *
 */
@Api(description = "后台角色管理接口")
@RestController
@RequestMapping(value = "/admin/role", produces = "application/json;charset=UTF-8")
public class AdminRoleController extends BaseController {
    
    @Autowired
    private AppRoleService appRoleService;
    
    @Autowired
    private AppPermissionService appPermissionService;
    
    /**
     * @api {post} /admin/role/findAppRoleByPage 分页获取角色列表
     * @apiGroup admin-role
     * @apiName findAppRoleByPage
     * @apiDescription 分页获取角色列表，只会获取各门店下的数据，门店间相互隔离
     * @apiParam {int} pageIndex 第几页，必填
     * @apiParam {int} pageSize 每页大小，必填
     * @apiSuccessExample 成功返回:
     * {
     *     "status": "返回码，200：成功；500：失败；401：未登录",
     *     "msg": "提示信息",
     *     "data" : {
     *         "count":"总条数",
	 *     	   "pageCount":"总分页数",
	 *         "bussData" : [{
	 *             "id" : "Long-角色主键id", 
	 *             "roleKey" : "String-角色标识key",
	 *             "roleDescribe" : "String-角色描述",
	 *             "roleName" : "String-角色名称",
	 *             "roleType" : "String-角色类型",
	 *             "customerId" : "Long-门店id",
	 *             "topPermissionNames" : "String-拥有的权限集合描述",
	 *             "permissionIds" : ["//拥有的权限id列表，数组"]
	 *         }]
     *     }
     * }
     * @apiErrorExample 失败返回:
     * {
     *     "status": "返回码，200：成功；500：失败；401：未登录",
     *     "msg": "提示信息"
     * }
     */
    @ApiOperation("分页获取角色列表")
    @RequireLogin(userEnum = UserEnum.admin)
    @PostMapping(value = "/findAppRoleByPage")
    public RespJson<BaseData<AppRoleInfoDTO>> findAppRoleByPage(
          @RequestParam(value = "pageIndex") int pageIndex,
          @RequestParam(value = "pageSize") int pageSize) {
        RespJson respJson = getFailRtnMap("发生未知错误！");
        
        AppRole record = new AppRole();
        PageInfo<AppRoleInfoDTO> pageInfo = appRoleService.findAppRoleByPage(record, pageIndex, pageSize);
        
        PageData pageData = new PageData((int) pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
        respJson = getSuccessPageRtnMap("获取角色列表成功！", pageData);
        return respJson;
    }
    
    
    /**
     * @api {post} /admin/role/getAllAppPermission 获取所有权限列表
     * @apiGroup admin-role
     * @apiName getAllAppPermission
     * @apiDescription 获取所有权限列表，只会获取各门店下的数据，门店间相互隔离
     * @apiSuccessExample 成功返回:
     * {
     *     "status": "返回码，200：成功；500：失败；401：未登录",
     *     "msg": "提示信息",
     *     "data" : {
	 *         "bussData" : [{
	 *             "id" : "Long-权限id", 
	 *             "permissionName" : "String-权限名称",
	 *             "resourceId" : "String-关联的资源id",
	 *             "permissionType" : "String-权限类型（page:页面；ajax:ajax请求；button：按钮）",
	 *             "roleType" : "String-角色类型",
	 *             "menuUrl" : "String-菜单url，当权限类型为页面时有值返回",
	 *             "menuName" : "String-菜单名称，当权限类型为页面时有值返回",
	 *             "menuLevel" : "String-第几级菜单，当权限类型为页面时有值返回",
	 *             "childPermissions" : [{//子权限菜单列表
	 *                 "id" : "Long-权限id", 
	 *                 "permissionName" : "String-权限名称",
	 *                 "resourceId" : "String-关联的资源id",
	 *                 "permissionType" : "String-权限类型（page:页面；ajax:ajax请求；button：按钮）",
	 *                 "roleType" : "String-角色类型",
	 *                 "menuUrl" : "String-菜单url，当权限类型为页面时有值返回",
	 *                 "menuName" : "String-菜单名称，当权限类型为页面时有值返回",
	 *                 "menuLevel" : "String-第几级菜单，当权限类型为页面时有值返回"
	 *             }]
	 *         }]
     *     }
     * }
     * @apiErrorExample 失败返回:
     * {
     *     "status": "返回码，200：成功；500：失败；401：未登录",
     *     "msg": "提示信息"
     * }
     */
    @ApiOperation("获取所有权限列表")
    @RequireLogin(userEnum = UserEnum.admin)
    @PostMapping(value = "/getAllAppPermission")
    public RespJson<BaseData<List<AppPermissionInfoDTO>>> getAllAppPermission() {
        RespJson respJson = getFailRtnMap("发生未知错误！");
        List<AppPermissionInfoDTO> dataList = appPermissionService.getAllAppPermissions();
        BaseData baseData = new BaseData(dataList);
        respJson = getSuccessRtnMap("获取权限列表成功！", baseData);
        return respJson;
    }
    
    /**
     * @api {post} /admin/role/saveAppRole 保存角色与权限
     * @apiGroup admin-role
     * @apiName saveAppRole
     * @apiDescription 保存角色与角色对应的所有权限
     * @apiParam {Long} id 角色id，编辑角色时必填
     * @apiParam {String} roleName 角色名称，必填
     * @apiParam {String} roleDescribe 角色描述，选填
     * @apiParam {Array} permissionIds 选择的权限项id数组，注意是数组传过来即可，权限项是有一级和二级之分，如果选择了二级，那么要把一级的权限id也传过来
     * @apiSuccessExample 成功返回:
     * {
     *     "status": "返回码，200：成功；500：失败；401：未登录",
     *     "msg": "提示信息",
     *     "data" : {
	 *         "bussData" : null
     *     }
     * }
     * @apiErrorExample 失败返回:
     * {
     *     "status": "返回码，200：成功；500：失败；401：未登录",
     *     "msg": "提示信息"
     * }
     */
    @ApiOperation("保存角色与权限")
    @RequireLogin(userEnum = UserEnum.admin)
    @PostMapping(value = "/saveAppRole")
    public RespJson<BaseData> saveAppRole(
          @ApiParam("角色id，编辑角色时必填")
          @RequestParam(value = "id", required = false) Long id,
          @ApiParam("角色名称，必填")
          @RequestParam(value = "roleName") String roleName,
          @ApiParam("角色描述，选填")
          @RequestParam(value = "roleDescribe") String roleDescribe,
          @ApiParam("选择的权限项id数组，注意是数组传过来即可，权限项是有一级和二级之分，如果选择了二级，那么要把一级的权限id也传过来")
          @RequestParam(value = "permissionIds[]", required = false) List<Long> permissionIds) {
    	RespJson respJson = getFailRtnMap("发生未知错误！");
    	LocalUser userInfo = UserThreadLocal.getUserInfo();
    	Long userId = userInfo.getUserId();
    	
        if (StringUtils.isBlank(roleName)){
        	return getFailRtnMap("角色名称未填写！");
        }
        AppRoleInfoDTO appRoleInfo = new AppRoleInfoDTO();
        appRoleInfo.setId(id);
        appRoleInfo.setRoleName(roleName);
        appRoleInfo.setRoleDescribe(roleDescribe);
        appRoleInfo.setPermissionIds(permissionIds);
        appRoleInfo.setCreator(String.valueOf(userId));
        appRoleInfo.setModifier(String.valueOf(userId));
        
        boolean flag = appRoleService.saveAppRole(appRoleInfo);
        if(flag){
        	respJson = getSuccessRtnMap("保存角色与权限成功！", null);
        }else{
        	respJson = getFailRtnMap("保存角色与权限失败！");
        }
        return respJson;
    }
    
    
    /**
     * @api {post} /admin/role/getRoleInfoByRoleId 获取角色详情
     * @apiGroup admin-role
     * @apiName getRoleInfoByRoleId
     * @apiDescription 获取角色详情，只会获取各门店下的数据，门店间相互隔离
     * @apiParam {Long} roleId 角色id，即列表返回的id字段，必填
     * @apiSuccessExample 成功返回:
     * {
     *     "status": "返回码，200：成功；500：失败；401：未登录",
     *     "msg": "提示信息",
     *     "data" : {
     *         "count":"总条数",
	 *     	   "pageCount":"总分页数",
	 *         "bussData" : [{
	 *             "id" : "Long-角色主键id", 
	 *             "roleKey" : "String-角色标识key",
	 *             "roleDescribe" : "String-角色描述",
	 *             "roleName" : "String-角色名称",
	 *             "roleType" : "String-角色类型",
	 *             "customerId" : "Long-门店id",
	 *             "topPermissionNames" : "String-拥有的权限集合描述",
	 *             "permissionIds" : ["//拥有的权限id列表，数组"]
	 *         }]
     *     }
     * }
     * @apiErrorExample 失败返回:
     * {
     *     "status": "返回码，200：成功；500：失败；401：未登录",
     *     "msg": "提示信息"
     * }
     */
    @ApiOperation("获取角色详情")
    @RequireLogin(userEnum = UserEnum.admin)
    @PostMapping(value = "/getRoleInfoByRoleId")
    public RespJson<BaseData<AppRoleInfoDTO>> getRoleInfoByRoleId(
          @ApiParam("角色id，即列表返回的id字段，必填")
          @RequestParam(value = "roleId") Long roleId) {
    	RespJson respJson = getFailRtnMap("发生未知错误！");
    	
        if (roleId == null){
        	return getFailRtnMap("角色ID不能为空！");
        }
        
        AppRoleInfoDTO appRoleInfo = appRoleService.getRoleInfoByRoleId(roleId);
        if(null != appRoleInfo){
            BaseData baseData = new BaseData(appRoleInfo);
            respJson = getSuccessRtnMap("获取角色信息成功！", baseData);
        }
        return respJson;
    }
    
    
    /**
     * @api {post} /admin/role/deleteRoleByRoleId 删除角色记录
     * @apiGroup admin-role
     * @apiName deleteRoleByRoleId
     * @apiDescription 删除角色记录
     * @apiParam {Long} roleId 角色id，即列表返回的id字段，必填
     * @apiSuccessExample 成功返回:
     * {
     *     "status": "返回码，200：成功；500：失败；401：未登录",
     *     "msg": "提示信息",
     *     "data" : {
	 *         "bussData" : null
     *     }
     * }
     * @apiErrorExample 失败返回:
     * {
     *     "status": "返回码，200：成功；500：失败；401：未登录",
     *     "msg": "提示信息"
     * }
     */
    @ApiOperation("删除角色记录")
    @RequireLogin(userEnum = UserEnum.admin)
    @PostMapping(value = "/deleteRoleByRoleId")
    public RespJson<BaseData> deleteRoleByRoleId(
          @ApiParam("角色id，即列表返回的id字段，必填")
          @RequestParam(value = "roleId") Long roleId) {
    	RespJson respJson = getFailRtnMap("发生未知错误！");
    	
        if (roleId == null){
        	return getFailRtnMap("角色ID不能为空！");
        }
        
        boolean flag = appRoleService.deleteRoleByRoleId(roleId);
        if(flag){
            respJson = getSuccessRtnMap("删除角色信息成功！", null);
        }else{
        	respJson = getFailRtnMap("删除角色信息失败！");
        }
        return respJson;
    }
}
